// 错误信息解析工具

export interface ErrorInfo {
  line: number;
  column?: number;
  message: string;
  severity: 'error' | 'warning' | 'info';
}

export interface ParsedErrors {
  errors: ErrorInfo[];
  rawErrorInfo: string;
}

/**
 * 解析编译错误信息
 * 支持GCC/Clang格式的错误信息
 */
export function parseCompileErrors(errorInfo: string): ParsedErrors {
  if (!errorInfo || typeof errorInfo !== 'string') {
    return { errors: [], rawErrorInfo: errorInfo || '' };
  }

  const errors: ErrorInfo[] = [];
  const lines = errorInfo.split('\n');
  
  for (const line of lines) {
    // 匹配GCC/Clang格式的错误信息
    // 格式: /path/to/file.cpp:line:column: error: message
    const errorMatch = line.match(/^[^:]+:(\d+):(\d+)?:\s*(error|warning|note):\s*(.+)$/);
    
    if (errorMatch) {
      const [, lineStr, columnStr, severity, message] = errorMatch;
      const lineNum = parseInt(lineStr, 10);
      const column = columnStr ? parseInt(columnStr, 10) : undefined;
      
      // 只处理error和warning，忽略note
      if (severity === 'error' || severity === 'warning') {
        errors.push({
          line: lineNum,
          column,
          message: message.trim(),
          severity: severity as 'error' | 'warning'
        });
      }
    }
  }

  return {
    errors,
    rawErrorInfo: errorInfo
  };
}

/**
 * 从调试结果中提取错误信息
 */
export function extractErrorsFromDebugResult(debugResult: any): ParsedErrors {
  if (!debugResult || !debugResult.statistic_info) {
    return { errors: [], rawErrorInfo: '' };
  }

  const errInfo = debugResult.statistic_info.err_info;
  if (!errInfo) {
    return { errors: [], rawErrorInfo: '' };
  }

  return parseCompileErrors(errInfo);
}

/**
 * 检查是否为编译错误
 */
export function isCompileError(result: number): boolean {
  return result === -2; // 编译错误状态码
}
